<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\BaseController;
use app\lib\exception\BaseException;
use app\model\Users;
use app\validate\api\ForgetPassword;
use dh2y\qrcode\QRcode;


class Register extends BaseController
{

    public  function  index()
    {
        (new \app\validate\api\Register())->goCheck();
        $params = request()->param();
        $params['password']=password_hash($params['password'],PASSWORD_DEFAULT);
        $user= Users::create($params);
        $code=new QRcode();
        $filePath =$code->png('用戶ID：'.$user->id,false, 6)->getPath(false);
        Users::where('id',$user->id)->update(['qrcode'=>ossUpload($filePath)]);
        return  $this->success();
    }


    /**
     * 忘记密码
     * @return \think\response\Json
     * @throws \app\lib\exception\BaseException
     */
    public function forgetPassword()
    {
        (new ForgetPassword())->goCheck();
        $params=request()->param(['mobile','password']);
        $params['password']=password_hash($params['password'],PASSWORD_DEFAULT);
        Users::where('mobile',$params['mobile'])->update($params);
        return $this->success();
    }

    public function logout()
    {
        return view();
    }

    public function cancel()
    {
        $mobile = request()->param('mobile',null);
        $password = request()->param('password',null);
        $user = Users::where('mobile', $mobile)->find();
        if (!$user){
            return redirect('/api/register/logout');
        }
        if (!password_verify($password, $user->password)) {
            return redirect('/api/register/logout');
        }
        Users::where('id',$user->id)->delete();

        return redirect('/api/register/logout');
    }
}
